package yunjiao.javatutorials.guava.concurrent;

import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 异常处理最佳实践
 *
 * @author yangyunjiao
 */
public class ExceptionHandlingExample {
    public static String riskyOperation(int input) throws Exception {
        if (input < 0) {
            throw new IllegalArgumentException("输入不能为负数");
        }
        Thread.sleep(input * 1000L);
        return "处理结果: " + input;
    }

    public static void main(String[] args) {
        TimeLimiter timeLimiter = SimpleTimeLimiter.create(
                Executors.newCachedThreadPool()
        );

        try {
            String result = timeLimiter.callWithTimeout(() -> {
                try {
                    return riskyOperation(4);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }, 3, TimeUnit.SECONDS);

            System.out.println(result);

        } catch (TimeoutException e) {
            System.out.println("操作超时，请重试");
        } catch (UncheckedTimeoutException e) {
            System.out.println("未检查超时异常");
        } catch (RuntimeException e) {
            if (e.getCause() instanceof IllegalArgumentException) {
                System.out.println("参数错误: " + e.getCause().getMessage());
            } else {
                System.out.println("运行时异常: " + e.getMessage());
            }
        } catch (Exception e) {
            System.out.println("其他异常: " + e.getMessage());
        }
    }
}
